import axios from 'axios'
import router from '../../router'
import Vue from 'vue'
import {ToastPlugin, LoadingPlugin} from 'vux'

Vue.use(ToastPlugin)
Vue.use(LoadingPlugin)

axios.defaults.baseURL = '/api/'
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.method = "post"
axios.defaults.timeout = 5000;

export default (url, data, successCallBack, showLoading, showSuccess) => {
    let t = 0
    if (showLoading) {
        Vue.$vux.loading.show()

        t = new Date().getTime()
    }
    axios.post(url, data
    ).then(response => {
        if (showLoading) {
            //延迟隐藏loading
            let d = 500 - (new Date().getTime() - t)
            if (d <= 0) {
                Vue.$vux.loading.hide()
            }
            else {
                setTimeout(() => {
                    Vue.$vux.loading.hide()
                }, d)
            }
        }
        if (response.data.resultCode === '1') {
            successCallBack(response.data.content)
            if (showSuccess) {
                Vue.$vux.toast.show({
                    text: '成功',
                    type: 'success'
                })
            }
        }
        else if (response.data.resultCode === '10021007') {
            router.push('/login')
        }
        else {
            Vue.$vux.toast.show({
                text: response.data.resultMsg,
                type: 'text',
                position: 'middle',
                time: 3000,
                width: '12em'
            })
        }

    }).catch(function (error) {
        console.log(error)
        if (showLoading) {
            Vue.$vux.loading.hide()
        }
        Vue.$vux.toast.show({
            text: '系统繁忙，请稍后再试',
            type: 'text',
            position: 'middle',
            width: '12em'
        })
    });
}
